import { defineStore } from 'pinia';

interface UserInfo {
    id: number;
    username: string;
    avatar?: string;
}

export const useUserStore = defineStore('user', () => {
    const userInfo = ref<UserInfo | null>(null);
    const accessToken = ref<string>('');
    const refreshToken = ref<string>('');

    // 设置token
    const setTokens = (params: { accessToken: string; refreshToken: string }) => {
        accessToken.value = params.accessToken;
        refreshToken.value = params.refreshToken;
    };

    // 清除token
    const clearTokens = () => {
        accessToken.value = '';
        refreshToken.value = '';
    };

    // 获取用户信息
    const fetchUserInfo = async () => {
        try {
        } catch (error) {
            clearTokens();
            throw error;
        }
    };

    // 登录
    const login = async (params: { username: string; password: string }) => {
        try {
            // 登录

            // 设置token
            setTokens({
                accessToken: '123',
                refreshToken: '456',
            });
            // 获取用户信息
            await fetchUserInfo();
        } catch (error) {
            clearTokens();
            throw error;
        }
    };

    // 登出
    const logout = async () => {
        try {
            // 登出

            // 清除用户信息
            userInfo.value = null;
            // 清除token
            clearTokens();
            // 跳转登录页
            await navigateTo('/user/login');
        } catch (error) {
            clearTokens();
            throw error;
        }
    };

    return {
        userInfo,
        accessToken,
        refreshToken,

        setTokens,
        clearTokens,
        fetchUserInfo,
        login,
        logout,
    };
});
